package com.catsic.base.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.catsic.base.exception.CatsicException;
import com.catsic.base.exception.CatsicExceptionCode;

public class FtpUtils {
	
	private FTPClient ftpClient;  
    private String ip;  
    private int port;  
    private String username;  
    private String password;  
  
    public static Logger logger = LoggerFactory.getLogger(FtpUtils.class);
  
    /** 
     * FtpUtils构造函数 
     */  
    public FtpUtils(String ip, int port, String username, String password) {  
        this.ip = ip;  
        this.port = port;  
        this.username = username;  
        this.password = password;  
        this.ftpClient = new FTPClient();  
    }  
    /** 
     * 登陆 
     * */  
    public void login() {  
        FTPClientConfig ftpClientConfig = new FTPClientConfig();  
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());  
        this.ftpClient.setControlEncoding("UTF-8");  
        this.ftpClient.configure(ftpClientConfig);  
        try {  
            if (this.port > 0) {  
                this.ftpClient.connect(this.ip, this.port);  
            } else {  
                this.ftpClient.connect(this.ip);  
            }  
            /**
             * FTP服务器连接回答  
             */
            int reply = this.ftpClient.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                this.ftpClient.disconnect();  
                logger.error("FTP服务登录失败！"); 
                throw new CatsicException(CatsicExceptionCode.FTP服务器登录失败);
            }  
            this.ftpClient.login(this.username, this.password);  
            /**
             * 设置传输协议  
             */
            this.ftpClient.enterLocalPassiveMode();  
            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
            logger.info("FTP服务器登陆成功");  
        } catch (Exception e) { 
        	logger.info("FTP服务器登录失败！");  
            logger.error(e.getMessage());  
            throw new CatsicException(CatsicExceptionCode.FTP服务器登录失败);
        }  
        this.ftpClient.setBufferSize(1024 * 2);  
        this.ftpClient.setDataTimeout(30 * 1000);  
    }  
  
    /** 
     * @退出关闭服务器链接 
     * */  
    public void exit() {  
        if (null != this.ftpClient && this.ftpClient.isConnected()) {  
            try {  
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器  
                if (reuslt) {  
                    logger.info("FTP服务器退出成功");  
                }  
            } catch (IOException e) {  
            	logger.info("FTP服务器退出失败！");  
                logger.error(e.getMessage());  
                throw new CatsicException(CatsicExceptionCode.FTP服务器退出失败);
            } finally {  
                try {  
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接  
                } catch (IOException e) {  
                	logger.info("FTP服务器连接关闭失败！");  
                    logger.error(e.getMessage());  
                    throw new CatsicException(CatsicExceptionCode.FTP服务器关闭失败);
                }  
            }  
        }  
    }
    
    /*** 
     * 上传Ftp文件 
     * @param fileName 文件名
     * @param inputStream 输入流
     * @param path FTP服务器存储目录
     * */  
    public void upload(String fileName,InputStream inputStream, String path) { 
    	login();
        BufferedInputStream inStream = null;  
        boolean success = false;  
        try {  
            this.ftpClient.changeWorkingDirectory(path);
            success = this.ftpClient.storeFile(fileName, inputStream);  
            if (success == false) {  
            	throw new CatsicException(CatsicExceptionCode.FTP文件上传失败);
            }  
        } catch (Exception e) { 
        	logger.info("文件上传失败！");  
            logger.error(e.getMessage());  
            throw new CatsicException(CatsicExceptionCode.FTP文件上传失败);
        } finally {  
        	exit();
            if (inStream != null) {  
                try {  
                    inStream.close();  
                } catch (IOException e) {  
                	logger.info("文件上传失败！");  
                    logger.error(e.getMessage());  
                    throw new CatsicException(CatsicExceptionCode.FTP文件上传失败);
                }  
            }  
        }
    }
    
    /*** 
     * 下载文件 
     * @param fileName 文件名
     * @param outputStream 输出流
     * @param path FTP服务器存储目录
     * */  
    public void download(String fileName, OutputStream outputStream, String path) {
    	login();
        boolean success = false;  
        try {  
            this.ftpClient.changeWorkingDirectory(path);  
            success = this.ftpClient.retrieveFile(fileName, outputStream);  
        } catch (Exception e) {  
        	logger.info("文件下载失败！");  
            logger.error(e.getMessage());  
            throw new CatsicException(CatsicExceptionCode.FTP文件下载失败);
        } finally {  
        	exit();
            if (null != outputStream) {  
                try {  
                	outputStream.flush();  
                	outputStream.close();  
                } catch (IOException e) {  
                	logger.info("文件下载失败！");  
                    logger.error(e.getMessage());  
                    throw new CatsicException(CatsicExceptionCode.FTP文件下载失败);
                }  
            }  
        }  
        if (success == false) {  
        	logger.info("文件下载失败！");  
        	throw new CatsicException(CatsicExceptionCode.FTP文件下载失败);
        }  
    }
    
    /*** 
     * 删除文件 
     * @param fileName   文件名称 
     * @param path FTP服务器存储目录
     * */  
    public void delete(String fileName,String path) {
    	login();
        boolean success = false;  
        try {  
            this.ftpClient.changeWorkingDirectory(path);  
            success = this.ftpClient.deleteFile(fileName);  
        } catch (Exception e) {  
        	logger.info("文件删除失败！");  
            logger.error(e.getMessage());  
            throw new CatsicException(CatsicExceptionCode.FTP文件删除失败);
        } finally {  
        	exit();
        } 
        
        if (success == false) {  
        	logger.info("文件删除失败！");  
        	throw new CatsicException(CatsicExceptionCode.FTP文件删除失败);
        }
    }
 
    public FTPClient getFtpClient() {  
        return ftpClient;  
    }  
    
    public void setFtpClient(FTPClient ftpClient) {  
        this.ftpClient = ftpClient;  
    }  
      
    public static void main(String[] args) throws IOException {  
    	FtpUtils ftp=new FtpUtils("192.168.17.3",23,"javauser","111111"); 
    	InputStream inStream = new BufferedInputStream(new FileInputStream("D:\\logs\\logs.log"));  
        ftp.upload("logs.log",inStream,"");
        //ftp.delete("logs.log", "");
        
    } 

}
